<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/layui/css/layui.css" media="all">
</head>
<style>
    .layui-table-cell{
        height:50px;
        line-height: 50px;
    }
</style>
<body>

<div id="layer-photos-demo" class="layer-photos-demo" style="display: none">

</div>

<form style="display: none" id="goodsForm" class="layui-form layui-form-pane"    lay-filter="goodsForm">
    <input type="text" name="goodsid" style="display: none">
    <div class="layui-collapse">
        <div class="layui-colla-item">
            <h2 class="layui-colla-title">图片</h2>
            <div class="layui-colla-content layui-show">
                <div id="showImg">

                </div>
            </div>
        </div>
    </div>
    <label class="layui-form-label">添加图片</label>
    <input class="layui-btn layui-btn-sm" type="file" id="img1"style="width:190px" name="main">
    <br>
    <br>
    <div class="layui-form-item">
        <label class="layui-form-label">商品名称</label>
        <div class="layui-input-inline">
            <input type="text" name="goodsname" id="goodsname" lay-verify="required" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">键盘布局</label>
        <div class="layui-input-inline">
            <input type="text" name="layout" lay-verify="required" placeholder="请输入键盘布局" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">键帽类型</label>
        <div class="layui-input-inline">
            <select id="keycapidSelect"  name="keycapid">
                <option value="">--键帽类型--</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">键盘颜色</label>
        <div class="layui-input-inline">
            <select id="keyboardcoloridSelect"  name="keyboardcolorid">
                <option value="">--键盘颜色--</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">轴体类型</label>
        <div class="layui-input-inline">
            <input type="text" name="shafttype" lay-verify="required" placeholder="请输入轴体类型" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">轴体选择</label>
        <div class="layui-input-inline">
            <select id="shaftchooseidSelect"  name="shaftchooseid">
                <option value="">--轴体选择--</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">接口类型</label>
        <div class="layui-input-inline">
            <input type="text" name="interfacetype" lay-verify="required" placeholder="请输入接口类型" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">背光颜色</label>
        <div class="layui-input-inline">
            <select id="backlightcoloridSelect"  name="backlightcolorid">
                <option value="">--背光颜色--</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品进价</label>
        <div class="layui-input-inline">
            <input type="text" name="cprice" id="cprice" lay-verify="required" placeholder="请输入商品进价" autocomplete="off" class="layui-input" onblur="numbers2(this)">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">商品售价</label>
        <div class="layui-input-inline">
            <input type="text" name="sprice" id="sprice" lay-verify="required" placeholder="请输入商品售价" autocomplete="off" class="layui-input" onblur="numbers2(this)">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">类别</label>
        <div class="layui-input-inline">
            <select name="state" id="state">
                <option value="">--状态--</option>
                <option value="0">下架状态</option>
                <option value="1">在售状态</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" id="TiJiao" lay-submit lay-filter="formDemo">立即提交</button>
            <a onclick="delInsert()" class="layui-btn layui-btn-primary">重置</a>
        </div>
    </div>
</form>

<div class="demoTable layui-form">
    <div class="layui-inline">
        <input class="layui-input" name="goodsname" id="goodsnameSel" placeholder="键盘名" autocomplete="off">
    </div>
    <div class="layui-inline" style="margin-top: 15px">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <select id="keycapidSel" name="keycapid" lay-verify="required">
                    <option value="">-请选择键帽类型-</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-inline" style="margin-top: 15px">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <select id="keyboardcoloridSel" name="keyboardcolorid" lay-verify="required">
                    <option value="">-请选择键盘颜色-</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-inline" style="margin-top: 15px">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <select id="shaftchooseidSel" name="shaftchooseid" lay-verify="required">
                    <option value="">-请选择轴体类型-</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-inline" style="margin-top: 15px">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <select id="backlightcoloridSel" name="backlightcolorid" lay-verify="required">
                    <option value="">-请选择背光颜色-</option>
                </select>
            </div>
        </div>
    </div>

    <div class="layui-inline" style="margin-top: 15px">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <select id="branchidSel" name="branchid" lay-verify="required">
                    <option value="">-请选择分店-</option>
                </select>
            </div>
        </div>
    </div>

    <button class="layui-btn" id="reloadTabBtn" data-type="reload">搜索</button>
</div>


<table class="layui-hide "  id="test" lay-filter="test"></table>


<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <%--        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>--%>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">刷新</button>
        {{#  if(${sessionScope.staff.branchid} == 12138){ }}
        <button class="layui-btn layui-btn-sm" id="addBtn" lay-event="addGoods">新增</button>
        {{#  } else { }}
        {{#  } }}
    </div>
</script>

<script type="text/html" id="barDemo">
    {{#  if(${sessionScope.staff.branchid} == 12138){ }}
    <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>
    {{#  } else { }}
    {{#  } }}
    <a class="layui-btn layui-btn-danger layui-btn-sm" id="del"  lay-event="del">删除</a>
    <%--{{#  if(d.state == 0){ }}
    <button class="layui-btn layui-btn-sm" lay-event="updateStatus">上架</button>
    {{#  } else { }}
    <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="updateStatus">下架</button>
    {{#  } }}--%>
</script>

<script type="text/html" id="titleTpl">
    {{#  if(d.state == 1){ }}
    <button class="layui-btn layui-btn-radius layui-btn-normal ">在售</button>
    {{#  } else { }}
    <button class="layui-btn layui-btn-radius layui-btn-danger ">未售</button>
    {{#  } }}
</script>
<script src="${pageContext.request.contextPath}/js/jquery-2.1.0.js"></script>
<script src="${pageContext.request.contextPath}/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->

<script>
    function numbers(a) {
        if (a.value==null||a.value==""){
        }else if (!(/(^[1-9]\d*$)/.test(a.value))) {
            layer.msg('请输入一个正整数', {icon: 5});
            a.value="";
        }
    }

    function numbers2(a) {
        if (a.value==null||a.value==""){
        }else if (!(/(^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$)/.test(a.value))) {
            layer.msg('请输入正确价格', {icon: 5});
            a.value="";
        }
    }

    function delInsert(){
        $("#showImg").empty()//清除图片
        $("#goodsForm")[0].reset();//清除表单中输入框数据
        return false;
    };

    layui.use(['table','jquery','form','layer','laydate','element','upload'], function(){
        var table = layui.table;
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var laydate= layui.laydate;
        var element = layui.element;
        var upload = layui.upload;


        img1.onchange=function () {
            /**
             * 创建二进制流
             */
            let reader = new FileReader();
            /**
             *二进制流读取图片
             */
            reader.readAsDataURL(img1.files[0]);
            /**
             * 把图片显现出来
             */
            reader.onload=function () {
                /*$('#showImg').append($('<img width="50px"height="50px">').prop('src',reader.result))*/
                $("#showImg").append(
                    $("<img>").prop('src', reader.result).prop('width',100).prop('height',50)
                );
            }
        }

        laydate.render({
            elem: '#date',
            type: 'datetime'//指定元素
        });

        table.render({
            id:'tb',
            elem: '#test'
            ,url:'${pageContext.request.contextPath}/goods/getAllGoods'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,title: '用户数据表'
            ,text: {
                none: '该分店还没有商品～' //默认：无数据。
            }
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'goodsid', title:'商品编号',fixed: 'left',hide:true/*,templet:function (data){
                    return data.branch_goods.goodsid
                    }*/}
                ,{field:'url', title:'商品图片',height:50,templet:function (data) {
                        var a=data.url
                        return "<Img src='"+a+"' style='width: 100px;height: 50px'>"
                    }}
                ,{field:'goodsname', title:'商品名称'}
                ,{field:'layout', title:'键盘布局'}
                ,{field:'goods.keycap', title:'键帽材质',templet: function (data) {
                        //console.log(data);
                        return data==null?"":data.keycap.keycapname;
                    }}
                ,{field:'goods.keyboardcolor', title:'键盘颜色',templet: function (data) {
                        //console.log(data);
                        return data==null?"":data.keyboardcolor.keyboardcolorname;
                    }}
                ,{field:'shafttype', title:'轴体类型'}
                ,{field:'goods.shaftchoose', title:'轴体选择',templet: function (data) {
                        //console.log(data);
                        return data==null?"":data.shaftchoose.shaftchoose;
                    }}
                ,{field:'interfacetype', title:'接口类型'}
                ,{field:'goods.backlightcolor', title:'背光颜色',templet: function (data) {
                        //console.log(data);
                        return data==null?"":data.backlightcolor.backlightcolorname;
                    }}
                ,{field:'cprice', title:'商品进价'}
                ,{field:'sprice', title:'商品售价'}
                ,{field:'branchname', title:'店铺名称'}
                ,{field:'counts', title:'商品数量'}
                /*,{field:'state', title:'状态' ,templet:'#titleTpl'}*/
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
            ]]
            ,page: true
            ,limit:8
            ,limits:[8,16,24]
        });

        $("#reloadTabBtn").click(function (){
            table.reload('tb',{
                where: { //设定异步数据接口的额外参数
                    goodsname:$("#goodsnameSel").val()
                    ,keycapid:$("#keycapidSel").val()
                    ,keyboardcolorid: $("#keyboardcoloridSel").val()
                    ,shaftchooseid:$("#shaftchooseidSel").val()
                    ,backlightcolorid:$("#backlightcoloridSel").val()
                    ,branchid:$("#branchidSel").val()
                }
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        })

        $.ajax({
            type:'post',
            url: '${pageContext.request.contextPath}/type/getAllKeyCap',
            dataType:'json',
            success:function (types){
                $.each(types,function (i,obj){
                    $("#keycapidSel").append(
                        $("<option></option>").attr('value',obj.keycapid).text(obj.keycapname)
                    )
                    $("#keycapidSelect").append(
                        $("<option></option>").attr('value',obj.keycapid).text(obj.keycapname)
                    )
                })
                form.render('select')
            }
        })

        $.ajax({
            type:'post',
            url: '${pageContext.request.contextPath}/type/getAllKeyBoardColor',
            dataType:'json',
            success:function (types){
                $.each(types,function (i,obj){
                    $("#keyboardcoloridSel").append(
                        $("<option></option>").attr('value',obj.keyboardcolorid).text(obj.keyboardcolorname)
                    )
                    $("#keyboardcoloridSelect").append(
                        $("<option></option>").attr('value',obj.keyboardcolorid).text(obj.keyboardcolorname)
                    )
                })
                form.render('select')
            }
        })
        $.ajax({
            type:'post',
            url: '${pageContext.request.contextPath}/type/getAllShaftChoose',
            dataType:'json',
            success:function (types){
                $.each(types,function (i,obj){
                    $("#shaftchooseidSel").append(
                        $("<option></option>").attr('value',obj.shaftchooseid).text(obj.shaftchoose)
                    )
                    $("#shaftchooseidSelect").append(
                        $("<option></option>").attr('value',obj.shaftchooseid).text(obj.shaftchoose)
                    )
                })
                form.render('select')
            }
        })
        $.ajax({
            type:'post',
            url: '${pageContext.request.contextPath}/type/getAllBacklightColor',
            dataType:'json',
            success:function (types){
                $.each(types,function (i,obj){
                    $("#backlightcoloridSel").append(
                        $("<option></option>").attr('value',obj.backlightcolorid).text(obj.backlightcolorname)
                    )
                    $("#backlightcoloridSelect").append(
                        $("<option></option>").attr('value',obj.backlightcolorid).text(obj.backlightcolorname)
                    )
                })
                form.render('select')
            }
        })
        $.ajax({
            type:'post',
            url: '${pageContext.request.contextPath}/type/getAllBacklightColor',
            dataType:'json',
            success:function (types){
                $.each(types,function (i,obj){
                    $("#backlightcoloridSel").append(
                        $("<option></option>").attr('value',obj.backlightcolorid).text(obj.backlightcolorname)
                    )
                    $("#backlightcoloridSelect").append(
                        $("<option></option>").attr('value',obj.backlightcolorid).text(obj.backlightcolorname)
                    )
                })
                form.render('select')
            }
        })
        $.ajax({
            url: '${pageContext.request.contextPath}/type/getAllType',
            type: 'get',
            dataType: 'json',
            success: function (types) {
                console.log(types)
                $.each(types, function (i, obj) {
                    $("#branchidSel").append(
                        $("<option></option>").attr("value", obj.branchid).text(obj.branchname)
                    )
                    $("#branchid").append(
                        $("<option></option>").attr("value", obj.branchid).text(obj.branchname)
                    )
                })
                form.render('select');
            }
        })
        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    table.reload('tb')
                    break;
                case 'addGoods':
                    $("#goodsForm")[0].reset();//清除表单中输入框数据
                    $("#showImg").empty()//清除图片
                    layer.open({
                        type:1,
                        title:'新增商品信息',
                        area:['400px','620px'],
                        offset:'0px',
                        anim:4,
                        content:$("#goodsForm"),
                    })
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            };
        });

        var sub=0;
        form.on('submit(formDemo)', function(data){
            var formData = new FormData(document.getElementById("goodsForm"));
            /* alert(formData)
             console.log(data.field) *///当前容器的全部表单字段，名值对形式：{name: value}
            if(sub == 0) {
                layer.msg('上传中', {
                    time: false,
                    icon: 16,
                    shade: 0.8
                });
                $.ajax({
                    type: 'post',
                    url: '${pageContext.request.contextPath}/goods/addOrUpdateGoods',
                    dataType: 'json',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (result) {
                        layer.closeAll();
                        if (result.code == 1) {
                            layer.msg(result.msg)
                        } else {
                            layer.msg(result.msg)
                        }
                        table.reload('tb')
                    }
                })
                return false;//阻止表单跳转。如果需要表单跳转，去掉这段即可。
            }else {
                alert("请输入正确格式")
            }
        });

        /*商品名称验证*/
        //$("#goodsname").bind("input",function (){
        $("#goodsname").blur(function () {
            $.post("${pageContext.request.contextPath}/goods/getGoodsName",{"goodsname":$("#goodsname").val()},function (backdata) {
                if(backdata.code==2){
                    sub=sub+1;
                    layer.msg('该商品名已存在，请重新填写',{icon: 5})
                    $("#TiJiao").attr("disabled",true)
                }else {
                    sub=0;
                    $("#TiJiao").attr("disabled",false)
                }
            }, 'json')
        });

        /*商品价格验证*/
        //$("#goodsname").bind("input",function (){
        $("#cprice").blur(function () {
            var sp=$("#sprice").val();
            var cp=$("#cprice").val();
            //alert(cp+"====="+sp)
            if(cp!="" && sp!=""){
                if(sp<=0 || cp<=0){
                    sub=sub+1;
                    layer.msg('这个定价认真的？？？')
                    $("#TiJiao").attr("disabled",true)
                }else if(cp-sp>=0){
                    sub=sub+1;
                    layer.msg('亏本大甩卖');
                    $("#TiJiao").attr("disabled",true)
                }else if(cp < sp){
                    sub=0;
                    $("#TiJiao").attr("disabled",false)
                }
            }else {
                sub=sub+1;
            }
        });

        $("#sprice").blur(function (a) {
            var sp=$("#sprice").val();
            var cp=$("#cprice").val();
            // alert(cp+"====="+sp)
            if(cp!="" && sp!=""){
                if(sp<=0 || cp<=0){
                    sub=sub+1;
                    layer.msg('这个定价认真的？？？')
                    $("#TiJiao").attr("disabled",true)
                }else if(cp-sp>=0){
                    sub=sub+1;
                    layer.msg('亏本大甩卖');
                    $("#TiJiao").attr("disabled",true)
                }else{
                    sub=0;
                    $("#TiJiao").attr("disabled",false)
                }
            }else {
                sub=sub+1;
            }
        });


        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除该商品吗？', function(index){
                    if (data.counts>0){
                        layer.msg("该商品还有库存，无法删除！")
                        $("#del").attr('disabled',true)
                    }else {
                        $.ajax({
                            type:'get',
                            url:'${pageContext.request.contextPath}/goods/delGoodsById',
                            data:{'goodsid':data.goodsid,"branchid":data.branchid},
                            dataType: 'json',
                            success:function (result){
                                if (result.code == 1) {
                                    layer.msg(result.msg)
                                }else {
                                    layer.msg(result.msg)
                                }
                                table.reload('tb')
                            }
                        })
                    }
                    layer.close(index);
                });
            } else if(obj.event === 'edit') {

                $("#goodsForm")[0].reset();
                layer.open({
                    type:1,
                    title:'修改商品信息',
                    area:['400px','600px'],
                    offset:'0px',
                    anim:4,
                    content:$("#goodsForm"),
                })
                form.val('goodsForm',data);
            }else if(obj.event === 'updateStatus'){
                layer.confirm('确定上架/下架吗?', function(index){
                    $.ajax({
                        type:'get',
                        url:'${pageContext.request.contextPath}/book/updateStatus',
                        data:{'bookid':data.bookid,'status':data.status},
                        dataType: 'json',
                        success:function (result){
                            if (result.code == 1) {
                                layer.msg(result.msg)
                            }else {
                                layer.msg(result.msg)
                            }
                            table.reload('tb')
                        }
                    })
                    layer.close(index);
                });
            }
        });
    });
</script>
</body>
</html>
